package utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpUtil {

    /**
     * 发送GET请求
     */
    public static String sendGet(String url) throws IOException {
        //创建HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Get请求
        HttpGet httpGet = new HttpGet(url);
        //请求头中添加User-Agent模拟设备访问
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36");

        //使用httpClient发送Get请求，获取响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //获取响应对象中的数据
        HttpEntity entity = response.getEntity();
        //将entity转为字符串
        String string = EntityUtils.toString(entity);

        //释放资源
        response.close();
        httpClient.close();

        return string;
    }
}
